import { Component, Host, h, Prop, ComponentInterface } from '@stencil/core';
import { commands } from '../../command';
import { Command, DataItemProvider, ICommandOption } from '../../interface';

@Component({
  tag: 'quick-action-list-item',
  styleUrl: 'quick-action-list-item.scss',
  shadow: true,
})
export class QuickActionListItem implements ComponentInterface {
  @Prop()
  active: boolean = false;

  @Prop()
  data: DataItemProvider;

  /**
   * 行内行为列表
   *
   * @author chitanda
   * @date 2022-06-28 18:06:55
   * @type {ICommandOption[]}
   */
  actions?: ICommandOption[];

  componentWillLoad() {
    if (this.data.actions) {
      this.actions = this.data.actions.map(action => this.getCommand(action));
    }
  }

  protected getCommand(command: string | Command): ICommandOption {
    let opt: ICommandOption;
    if (typeof command === 'string') {
      commands.hasCommand(command);
      opt = commands.getCommandOpts(command);
    } else {
      commands.hasCommand(command.command);
      opt = commands.getCommandOpts(command.command);
      opt = { ...opt, ...command };
    }
    if (opt) {
      return opt;
    }
  }

  /**
   * 行内行为点击
   *
   * @author chitanda
   * @date 2022-06-29 19:06:43
   * @param {MouseEvent} e
   * @param {ICommandOption} action
   */
  onActionClick(e: MouseEvent, action: ICommandOption): void {
    e.stopPropagation();
    commands.execute(action.id, this.data);
  }

  render() {
    return (
      <Host class={{ 'quick-action-list-item': true, active: this.active }} title={this.data.tooltip}>
        <div class='icon'>{this.data.icon ? <ion-icon src={this.data.icon} /> : null}</div>
        <div class='label'>{this.data.label}</div>
        <div class='description' title={this.data.description}>
          {this.data.description}
        </div>
        <div class='actions'>
          {this.actions &&
            this.actions.map(action => {
              return (
                <div class='action-item' title={action.tooltip} onClick={e => this.onActionClick(e, action)}>
                  <div class='action-item_icon'>
                    <ion-icon src={action.icon} />
                  </div>
                </div>
              );
            })}
        </div>
      </Host>
    );
  }
}
